<?php
include_once 'send_http_mssage.class.php';
include_once 'callback_notify.class.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/pass_queue/pass_queue.class.php';
include_once dirname(dirname(dirname(dirname(__FILE__)))) . '/np/np_http_curl.class.php';
include_once dirname(dirname(__FILE__)) . '/models/sp_model.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/video/vod.class.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/video/vod_index.class.php';
/**
 * 非媒资队列注入分派
 * @author LZ
 * @date 2017-02-27
 */
class import_queue
{
	private $dc=null;
	private $sp_id=null;

	public function __construct($dc)
	{
		$this->dc = $dc;
	}

	/**
	 * 透传队列注入
	 * @param $queue_info 注入数据
	 * @param $sp_info sp配置
	 * @author zhiyong.luo
	 * @date 2017-02-26
	 */
	public function import_pass_queue($queue_info,$sp_info)
    {
		if(empty($queue_info) || !is_array($sp_info) || !is_array($queue_info))
		{
			return false;
		}

		$this->sp_id = $sp_info['nns_id'];
//		$sp_config = json_decode($sp_info['nns_config'],true);
		$sp_config = $sp_info;
		if($sp_config['pass_queue_disabled'] != '1' || empty($sp_config['pass_queue_import_url'])) //未开启透传队列或未配置透传URL地址
		{
			return false;
		}

		$callback_notify = new callback_notify();
		//根据SP——id获取SP配置
		switch ($queue_info['nns_type'])
		{
			case '0'://栏目同步
				if(strlen($queue_info['nns_action'])<1)//栏目同步需要有行为动作
				{
					return false;
				}
				$info = array('m' => 'sync_asset_category/k380_b_1');
				$info['a'] = (int)$queue_info['nns_action'] === 1 ? 'add' : 'delete'; //1添加 3删除
				$url = $sp_config['pass_queue_import_url'] . '?' . http_build_query($info);
				$re = $this->post_data($url,array('data' => $queue_info['nns_content']));
				$re['bkmsgid'] = $queue_info['nns_id'];
				nn_log::write_log_message(LOG_PASS_QUEUE_MODEL, "通知结果为：" . var_export($re, true), $this->sp_id);
				$callback_notify->pass_queue_notify_v2($re,'xml');
				break;
			case '1'://栏目推荐
				if((int)$queue_info['nns_action'] === 0 || (int)$queue_info['nns_action'] === 2)//栏目推荐需要有行为动作
				{
					return false;
				}
				$info = array('m' => 'sync_asset_category/k380_a_1');
				$info['a'] = (int)$queue_info['nns_action'] === 1 ? 'maintain' : 'delete'; //1添加 3删除
				$url = $sp_config['pass_queue_import_url'] . '?' . http_build_query($info);
				$re = $this->post_data($url,array('data' => $queue_info['nns_content']));				
				break;
			case '2'://CP同步				
				if((int)$queue_info['nns_action'] !== 1)//栏目推荐需要有行为动作
				{
					return false;
				}
				$info = array(
						'm' => 'sync_asset_category/k381_a_1',
						'a' => 'add',
				);
				$url = $sp_config['pass_queue_import_url'] . '?' . http_build_query($info);
				$re = $this->post_data($url,json_decode($queue_info['nns_content'],true));
				break;
			case '3'://栏目图片同步
				if((int)$queue_info['nns_action'] === 0 || (int)$queue_info['nns_action'] === 2)//栏目推荐需要有行为动作
				{
					return false;
				}
				$info = array('m' => 'sync_asset_category/k380_b_1');
				$info['a'] = (int)$queue_info['nns_action'] === 1 ? 'add_img' : 'delete_img'; //1添加 3删除
				$url = $sp_config['pass_queue_import_url'] . '?' . http_build_query($info);
				$re = $this->post_data($url,array('data' => $queue_info['nns_content']));
				break;
			case '4'://媒资融合
				$info = array(
					'm' => 'fusion_assets/k382_a_1',
					'a' => 'record_data_to_database',
					'bk_msg_id' => $queue_info['nns_id']
				);
				$url = $sp_config['pass_queue_import_url'] . '?' . http_build_query($info);
				$re = $this->post_data($url,array('data' => $queue_info['nns_content']));
				break;
			case '5'://媒资打包关系 走k23接口
				//解析获取assetid
				$obj = simplexml_load_string($queue_info['nns_content']);
				$asset_info = json_decode(json_encode($obj), true);
				if(empty($asset_info["@attributes"]['assets_id']))
				{
					$re = array('ret' => 1,"reason"=>'打包关系解析失败');
					break;
				}
				$asset_id = $asset_info["@attributes"]['assets_id'];
				
				$data['func'] = 'modify_video';
				$data['assets_content']     = $queue_info['nns_content'];
				$data['assets_video_info']     = $queue_info['nns_content'];
				$data['asset_source_id'] = $asset_id;
				$data['assets_id'] = $asset_id;
				$re = $this->post_data_k23($sp_config['epg_url'],$data);
                $re['bkmsgid'] = $queue_info['nns_id'];
                $callback_notify->pass_queue_notify_v2($re,'xml');
				break;
			case '6'://录制节目单 走k23接口
				$data['func'] = 'import_vod_playbill';
				$data['playbill']     = $queue_info['nns_content'];
				$re = $this->post_data_k23($sp_config['epg_url'],$data);
				break;
			case '7'://媒资锁定解锁
				$data['func'] = 'lock_and_unlock_asset';
				$lock_info = json_decode($queue_info['nns_content'], true);
				$data['cp_id'] = $lock_info[0]['cp_id'];
				$data['assets_id'] = $lock_info[0]['assets_id'];
				$data['check'] = $lock_info[0]['check'];
				$data['assets_id_type'] = $lock_info[0]['assets_id_type'];
//				$data['output_type'] = 'json';
				$re = $this->post_data_k23($sp_config['epg_url'],$data);
				$re['bkmsgid'] = $queue_info['nns_id'];
				$callback_notify->pass_queue_notify_v2($re,'json');
				break;
            case '50': // 主媒资绑定或解绑定分集
                // 解析需要注入的xml信息，获取主媒资ID
                $obj = simplexml_load_string($queue_info['nns_content']);
                $arr_index_bind_info = json_decode(json_encode($obj), true);
                if (!isset($arr_index_bind_info['assets_id']) || strlen($arr_index_bind_info['assets_id']) == 0)
                {
                    $re = array('ret' => 1, 'reason' => '主媒资与分集绑定关系中，主媒资ID不存在');
                    return $re;
                }
                $str_assets_id = $arr_index_bind_info['assets_id'];

                // 组装请求K23接口需要的POST数据，请求K23接口
                $arr_data = array(
                    'func'              => 'bind_vod_index',
                    'assets_id'         => $str_assets_id,
                    'vod_index_list'    => $queue_info['nns_content']
                );
                $re = $this->post_data_k23($sp_config['epg_url'], $arr_data);
                break;
			case '98'://湖南电信/联通直播节目单注入
				$info = array(
					'func' => 'import_playbill_by_json',
					'identify' => 'live_ex=live_id|key=hndx_upstream_live_id|value=?',
//					'output_type'=> 'json',
				);
				$data = array('data'=>$queue_info['nns_content']);
				$data = array_merge($info,$data);
				$re = $this->post_data_k23($sp_config['epg_url'],$data);
				$re['bkmsgid'] = $queue_info['nns_id'];
				$callback_notify->pass_queue_notify_v2($re,'json');
				break;
			case '99'://湖南电信/联通直播频道锁定解锁
				$info = array(
					'm' => 'k24/k24_c_1',
					'a' => 'option_live_lock_state',
				);
				$url = $sp_config['pass_queue_import_url'] . '?' . http_build_query($info);
				$re = $this->post_data($url,array('data' => $queue_info['nns_content']));
				$re['bkmsgid'] = $queue_info['nns_id'];
				$callback_notify->pass_queue_notify_v2($re,'json');
				break;
            case '94'://湖南电信/联通花絮预告和正片的绑定关系
                $info = array(
                    'func' => 'import_video_index_bind',
                );
                $data = array('data'=>$queue_info['nns_content']);
                $data = array_merge($info,$data);
                $re = $this->post_data_k23($sp_config['epg_url'],$data);
                $re['bkmsgid'] = $queue_info['nns_id'];
                $callback_notify->pass_queue_notify_v2($re,'json');
                break;
            case '101'://爱上项目，上下线，通过透传，再注入到cdn
                include_once dirname(dirname(__FILE__)) . '/cntv_me/models/child_c2_task_model.php';
                if (empty($queue_info['nns_content']))
                {
                    $re['ret'] = 1;
                    break;
                }
                $pass_content = json_decode($queue_info['nns_content'], true);
                if ($pass_content['status'] == 1)
                {
                    $action = "ONLINE";
                }
                else
                {
                    $action = "OFFLINE";
                }
                $sp_config = sp_model::get_sp_config($this->sp_id);
                if (isset($sp_config['import_id_mode']) && strlen($sp_config['import_id_mode']) > 0 && (int)$sp_config['import_id_mode'] > 0)
                {
                    if ($sp_config['import_id_mode'] == 3)
                    {
                        $str_id = $sp_config['import_csp_id'].'000';
                        $len = strlen($str_id);
                        $integer_id = rtrim(substr($pass_content['original_id'], $len), '0');
                        $arr_params = array(
                            'nns_integer_id' => $integer_id,
                        );
                    }
                }
                else
                {
                    $arr_params = array(
                        'nns_asset_import_id' => $pass_content['original_id'],
                    );
                }
                if ($pass_content['asset_type'] == 4)//剧集头类型
                {
                    $vod_info = nl_vod::query_by_condition($this->dc, $arr_params);

                    if ($vod_info['ret'] != 0 || !is_array($vod_info['data_info']) || count($vod_info['data_info']) < 1)
                    {
                        $re['ret'] = 1;
                        break;
                    }
                    if ($vod_info['data_info'][0]['nns_all_index'] == 1)
                    {
                        //为电影时。直接走program,先查询当前电影的第一集的信息
                        $vod_index_info = nl_vod_index::get_vod_index_info($this->dc, $vod_info['data_info'][0]['nns_id'], 0);
                        if (empty($vod_index_info) || !is_array($vod_index_info) || count($vod_index_info) < 1)
                        {
                            $re['ret'] = 1;
                            break;
                        }
                        $vod_index_info[0]['nns_category_id'] = $vod_info['data_info'][0]['nns_category_id'];
                        $vod_index_info[0]['nns_name'] = $vod_info['data_info'][0]['nns_name'];
                        $obj_c2 = child_c2_task_model::do_program_line($vod_index_info[0], $action, $this->sp_id);
                    }
                    else
                    {
                        $vod_info['data_info'][0]['nns_series_flag'] = 0;
                        $obj_c2 = child_c2_task_model::do_series_line($vod_info['data_info'][0], $action, $this->sp_id);
                    }
                }
                elseif ($pass_content['asset_type'] == 5)//剧集
                {
                    $vod_index_info = nl_vod_index::query_by_condition($this->dc, $arr_params);
                    if ($vod_index_info['ret'] != 0 || !is_array($vod_index_info['data_info']) || count($vod_index_info['data_info']) < 1)
                    {
                        $re['ret'] = 1;
                        break;
                    }
                    $obj_c2 = child_c2_task_model::do_program_line($vod_index_info['data_info'][0], $action, $this->sp_id);
                }
                else
                {
                    $obj_c2 = false;
                }
                if ($obj_c2)
                {
                    $re['ret'] = 0;
                }
                else
                {
                    $re['ret'] = 1;
                }
                break;
            case '102'://主媒资修改，k23接口
                $data = json_decode($queue_info['nns_content'], true);
                $re = $this->post_data_k23($sp_config['epg_url'],$data);
                $re['bkmsgid'] = $queue_info['nns_id'];
                $callback_notify->pass_queue_notify_v2($re,'xml');
                break;
            case '103'://分集修改，k23接口
                $data = json_decode($queue_info['nns_content'], true);
                $re = $this->post_data_k23($sp_config['epg_url'],$data);
                $re['bkmsgid'] = $queue_info['nns_id'];
                $callback_notify->pass_queue_notify_v2($re,'xml');
                break;
            case '104'://明星库同步
                $data = urldecode($queue_info['nns_content']);
                $re = $this->post_star_data($sp_config['pass_queue_import_url'],$data);
                $re['bkmsgid'] = $queue_info['nns_id'];
                $callback_notify->pass_queue_notify_v2($re,'xml');
                break;
		}
		if($re['ret'] != 0)
		{
			nl_pass_queue::modify($this->dc,array('nns_status' => 3),array('nns_id' => $queue_info['nns_id']));
		}
		elseif ($re['ret'] == 0 && $queue_info['nns_type'] == '4') 
		{
			nl_pass_queue::modify($this->dc,array('nns_status' => 4),array('nns_id' => $queue_info['nns_id']));
		}
		else 
		{
			nl_pass_queue::modify($this->dc,array('nns_status' => 0),array('nns_id' => $queue_info['nns_id']));
		}
		return $re;
	}
	/**
	 * 透传队列注入
	 * @param $url 注入URL地址
	 * @param $data 注入数据
	 * @return array('ret','reason')
	 */
	private function post_data($url,$data)
	{
		$http_curl = new np_http_curl_class();
		nn_log::write_log_message(LOG_PASS_QUEUE_MODEL, "POST的URL" . $url . "请求参数：" . var_export($data, true), $this->sp_id);
		$re = $http_curl->post($url,$data);
		$curl_info = $http_curl->curl_getinfo();
		nn_log::write_log_message(LOG_PASS_QUEUE_MODEL, "curl状态结果：" . var_export($curl_info, true), $this->sp_id);
		$response = json_decode($re,true);
		nn_log::write_log_message(LOG_PASS_QUEUE_MODEL, "CMS返回结果为：" . var_export($response, true), $this->sp_id);
		if($curl_info['http_code'] != '200')
		{
			return array('ret' => 1 , 'reason' => 'POST接口失败,返回' . $curl_info['http_code']);
		}
		if($response['code'] != '0')
		{
			return array('ret' => 1 , 'reason' => $response['reason']);
		}
		return array('ret' => 0 , 'reason' => '成功');
	}
	/**
	 * 透传队列注入
	 * @param $url 注入URL地址
	 * @param $data 注入数据
	 * @return array('ret','reason')
	 */
	private function post_data_k23($url,$data)
	{
		$http_curl = new np_http_curl_class();
		nn_log::write_log_message(LOG_PASS_QUEUE_MODEL, "POST的URL" . $url . "请求参数：" . var_export($data, true), $this->sp_id);
		$re = $http_curl->post($url,$data);
		$curl_info = $http_curl->curl_getinfo();
		nn_log::write_log_message(LOG_PASS_QUEUE_MODEL, "curl状态结果：" . var_export($curl_info, true), $this->sp_id);
		$response = json_decode(json_encode(@simplexml_load_string($re)),true);
		nn_log::write_log_message(LOG_PASS_QUEUE_MODEL, "CMS返回结果为：" . var_export($response, true), $this->sp_id);
		if($curl_info['http_code'] != '200')
		{
			return array('ret' => 1 , 'reason' => 'POST接口失败,返回' . $curl_info['http_code']);
		}
		return array('ret' => $response['@attributes']['ret'] , 'reason' => $response['@attributes']['reason']);
	}

    /**
     * 透传队列注入
     * @param $url 注入URL地址
     * @param $data 注入数据
     * @return array('ret','reason')
     */
    private function post_star_data($url,$data)
    {
        $http_curl = new np_http_curl_class();
        nn_log::write_log_message(LOG_PASS_QUEUE_MODEL, "POST的URL" . $url . "请求参数：" . var_export($data, true), $this->sp_id);
        $temp_data['func'] = 'add_actor';
        $temp_data['actor_info'] = $data;
        $re = $http_curl->post($url,$temp_data);
        $curl_info = $http_curl->curl_getinfo();
        nn_log::write_log_message(LOG_PASS_QUEUE_MODEL, "curl状态结果：" . var_export($curl_info, true), $this->sp_id);
        $response = json_decode(json_encode(@simplexml_load_string($re)),true);
        nn_log::write_log_message(LOG_PASS_QUEUE_MODEL, "CMS返回结果为：" . var_export($response, true), $this->sp_id);
        if($curl_info['http_code'] != '200')
        {
            return array('ret' => 1 , 'reason' => 'POST接口失败,返回' . $curl_info['http_code']);
        }
        return array('ret' => $response['@attributes']['ret'] , 'reason' => $response['@attributes']['reason']);
    }

}